import json
import datetime
import pandas as pd
from django.contrib.auth.hashers import make_password
from django.contrib.auth import authenticate
from django.http import JsonResponse
from rest_framework import status
from rest_framework.response import Response
from rest_framework.decorators import api_view
from permissionmanagement.models import UserInfo
from toolkit.tools import send_email

@api_view(['POST'])
def register_user(request):
    data = request.data
    username = data.get('username')
    password = data.get('password')
    email = data.get('email')

    if UserInfo.objects.filter(username=username).exists():
        return Response({"error": "该账号已存在"}, status=status.HTTP_400_BAD_REQUEST)

    if UserInfo.objects.filter(email=email).exists():
        return Response({"error": "该邮箱已存在"}, status=status.HTTP_400_BAD_REQUEST)

    if len(password) < 8:
        return Response({"error": "密码长度不足。"}, status=status.HTTP_400_BAD_REQUEST)

    # 创建用户
    user = UserInfo(username=username, password=make_password(password),email=email)
    user.save()

    return Response({"message": "注册成功！欢迎来到DJ系统"}, status=status.HTTP_201_CREATED)

@api_view(['POST'])

def login_user(request):
    data = request.data
    username = data.get('username')
    password = data.get('password')

    # 检查用户是否存在
    if not UserInfo.objects.filter(username=username).exists():
        return Response({"error": "该账号不存在。"}, status=status.HTTP_400_BAD_REQUEST)

    # 验证用户和密码
    user = authenticate(username=username, password=password)
    if user is None:
        return Response({"error": "密码错误。"}, status=status.HTTP_400_BAD_REQUEST)

    # 管理员标识确认
    is_admin = 1 if user.is_superuser else 0

    # 登录成功
    return Response({"message": "登录成功！", "statusRoot": is_admin}, status=status.HTTP_200_OK)




@api_view(['POST'])
def forgot_password(request):
    data = request.data

    email = data.get('email')
    username = data.get('username')
    new_password = data.get('new_password')

    # 验证邮箱是否已经注册
    if not UserInfo.objects.filter(email=email).exists():
        return Response({"error": "邮箱未注册"}, status=status.HTTP_400_BAD_REQUEST)

    # 获取用户信息
    user = UserInfo.objects.filter(email=email).first()

    # 如果用户名不匹配
    if user.username != username:
        user.attempt_count += 1  # 增加尝试次数
        user.save()

        if user.attempt_count >= 3:
            # 当错误次数达到 3 次，发送账号信息邮件，并立即重置尝试次数
            send_email(user.username, email)
            user.attempt_count = 0  # 发送邮件后立即重置尝试次数
            user.save()
            return Response({"error": "用户名不正确，已将账号信息发送至您的邮箱"}, status=status.HTTP_400_BAD_REQUEST)

        return Response({"error": f"用户名不正确。您还有{3 - user.attempt_count}次尝试机会"}, status=status.HTTP_400_BAD_REQUEST)

    # 如果用户名匹配，则重置尝试次数
    user.attempt_count = 0
    user.save()

    # 检查密码长度
    if len(new_password) < 8:
        return Response({"error": "密码长度不足。"}, status=status.HTTP_400_BAD_REQUEST)

    # 更新密码并保存
    user.password = make_password(new_password)
    user.save()

    return Response({"message": "密码修改成功"}, status=status.HTTP_200_OK)


@api_view(['POST'])
def reset_attempt_count(request):
    # 重置所有用户的 attempt_count
    UserInfo.objects.update(attempt_count=0)
    return Response({"message": "所有用户的尝试次数已重置"}, status=status.HTTP_200_OK)



#管理员
@api_view(['POST'])
def query_user(request):
    user_info = UserInfo.objects.all().values('username', 'email', 'date_joined','is_superuser')
    # 将数据转换为 Pandas DataFrame
    df = pd.DataFrame(user_info)
    # df_category = df.loc[df['category'] == category]

    # 按照管理员字段排序
    df.sort_values(by="is_superuser", inplace=True, ascending=False)

    df['date_joined'] = df['date_joined'].apply(lambda x: x.strftime('%Y-%m-%d %H:%M:%S'))
    # df['date_joined'] = [datetime.datetime.fromtimestamp(x / 1000) for x in df['date_joined']]
    # 将 DataFrame 转换为 JSON 格式
    data_json = df.to_json(orient='records', force_ascii=False)

    # 将 JSON 返回给客户端
    return JsonResponse(json.loads(data_json), safe=False)

@api_view(['POST'])
def add_user(request):
    data = request.data
    username = data.get('username')
    password = data.get('password')
    email = data.get('email')
    is_superuser = data.get('is_superuser')

    if UserInfo.objects.filter(username=username).exists():
        return Response({"error": "该账号已存在"}, status=status.HTTP_400_BAD_REQUEST)

    if UserInfo.objects.filter(email=email).exists():
        return Response({"error": "该邮箱已存在"}, status=status.HTTP_400_BAD_REQUEST)

    if len(password) < 8:
        return Response({"error": "密码长度不足。"}, status=status.HTTP_400_BAD_REQUEST)

    # 创建用户
    user = UserInfo(username=username, password=make_password(password),email=email,is_superuser=is_superuser)
    user.save()

    return Response({"message": "添加成功！"}, status=status.HTTP_201_CREATED)
@api_view(['POST'])
def delete_user(request):
    data = request.data
    username = data.get('username')
    if not UserInfo.objects.filter(username=username).exists():
        return Response({"error": "该账号不存在"}, status=status.HTTP_400_BAD_REQUEST)
    user = UserInfo.objects.filter(username=username).first()
    user.delete()
    return Response({"message": "删除成功！"}, status=status.HTTP_200_OK)



@api_view(['POST'])
def update_user(request):
    data = request.data
    username = data.get('username')
    password = data.get('password')
    email = data.get('email')
    is_superuser_str = data.get('is_superuser')

    # 账号必须填，用于识别账户是否存在
    if not username:
        return Response({"error": "账号必须填写。"}, status=status.HTTP_400_BAD_REQUEST)

    if not UserInfo.objects.filter(username=username).exists():
        return Response({"error": "该账号不存在"}, status=status.HTTP_400_BAD_REQUEST)

    user = UserInfo.objects.filter(username=username).first()

    # 处理密码
    if password and len(password) < 8:
        return Response({"error": "密码长度不足。"}, status=status.HTTP_400_BAD_REQUEST)
    elif password:
        user.password = make_password(password)

    # 处理邮箱
    # 处理邮箱，如果新邮箱和旧邮箱相同或者新邮箱不存在于数据库中，则更新邮箱
    if email:
        if user.email == email:
            pass
        elif UserInfo.objects.filter(email=email).exists():
            return Response({"error": "该邮箱已被其他用户使用。"}, status=status.HTTP_400_BAD_REQUEST)
        else:
            user.email = email

    # 处理 is_superuser，只能输入 0 或 1，0 是 False，1 是 True
    if is_superuser_str is not None:
        if is_superuser_str in ('0', '1'):
            is_superuser = bool(int(is_superuser_str))
            user.is_superuser = is_superuser
        else:
            return Response({"error": "“is_superuser”值只能是 0 或 1。"}, status=status.HTTP_400_BAD_REQUEST)

    user.save()

    return Response({"message": "修改成功！"}, status=status.HTTP_200_OK)






